package com.skyeyemonitoring.activitys;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.skyeyemonitoring.R;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;

/**
 * 描述  远程功能更模块
 * Created by ${QQZ} on 2017/5/11.
 */

public class RemoteActivity extends AppCompatActivity implements View.OnClickListener , SensorEventListener {

    /** 车牌号 */
    private TextView mTvRemoteNumberPlate;

    /** 百度地图 */
    private MapView mMapViewRemote;
    private BaiduMap mBaiduMap;
    /** 定位 */
    public MyLocationListenner myListener = new MyLocationListenner();
    LocationClient mLocClient;

   /** 地图传回来的经纬度 */
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private Double lastX = 0.0;

    /** UI相关 */
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;

    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;

    /** 方向传感器 */
    private SensorManager mSensorManager;
    private static boolean isPermissionRequested = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermission();
        setContentView(R.layout.qqz_remote_aty);

        initView();


        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        //获取传感器管理服务
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //初始化百度地图
        mBaiduMap = mMapViewRemote.getMap();
        //启动定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();




    }


    private void initView() {
        mTvRemoteNumberPlate = (TextView) findViewById(R.id.tv_remote_number_plate);
        mTvRemoteNumberPlate.setText("渝A888888");
        mMapViewRemote = (MapView) findViewById(R.id.map_view_remote);

        mMapViewRemote.setOnClickListener(this);
        findViewById(R.id.llayou_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.overlook(0);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                Toast.makeText(RemoteActivity.this, "111", Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map_view_remote:
                break;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        double x = event.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder() .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapViewRemote == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }


    }
    @Override
    protected void onResume() {
        mMapViewRemote.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);

    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
//        .stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapViewRemote.onDestroy();
        mMapViewRemote = null;
        super.onDestroy();
    }
    private void requestPermission() {

        AndPermission.with(RemoteActivity.this).requestCode(100)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION
                        ,Manifest.permission.ACCESS_FINE_LOCATION
                        ,Manifest.permission.ACCESS_WIFI_STATE
                        ).rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int i, Rationale rationale) {
                // 此对话框可以自定义，调用rationale.resume()就可以继续申请。
                AndPermission.rationaleDialog(RemoteActivity.this, rationale).show();
            }
        }).callback(this).start();

//        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested) {
//
//            isPermissionRequested = true;
//
//            ArrayList<String> permissions = new ArrayList<>();
//            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
//            }
//
//            if (permissions.size() == 0) {
//                return;
//            } else {
//                requestPermissions(permissions.toArray(new String[permissions.size()]), 0);
//            }
//        }
    }


}
